"""
文件工具模块
"""

import os
from pathlib import Path
from typing import Optional, List
import urllib.request


class FileUtils:
    """文件工具类"""
    
    @staticmethod
    def ensure_dir(directory: str) -> Path:
        """
        确保目录存在，不存在则创建
        
        Args:
            directory: 目录路径
        
        Returns:
            Path: 目录路径对象
        """
        dir_path = Path(directory)
        dir_path.mkdir(parents=True, exist_ok=True)
        return dir_path
    
    @staticmethod
    def get_desktop_path() -> Path:
        """
        获取桌面路径
        
        Returns:
            Path: 桌面路径
        """
        desktop = Path.home() / "Desktop"
        if not desktop.exists():
            desktop = Path.home()
        return desktop
    
    @staticmethod
    def list_files(directory: str, pattern: str = "*") -> List[Path]:
        """
        列出目录中的文件
        
        Args:
            directory: 目录路径
            pattern: 文件匹配模式
        
        Returns:
            List[Path]: 文件路径列表
        """
        dir_path = Path(directory)
        if not dir_path.exists():
            return []
        
        return list(dir_path.glob(pattern))
    
    @staticmethod
    def get_file_size_str(file_path: str) -> str:
        """
        获取文件大小字符串
        
        Args:
            file_path: 文件路径
        
        Returns:
            str: 文件大小字符串（如 "1.5 MB"）
        """
        try:
            size = Path(file_path).stat().st_size
            
            for unit in ['B', 'KB', 'MB', 'GB']:
                if size < 1024.0:
                    return f"{size:.1f} {unit}"
                size /= 1024.0
            
            return f"{size:.1f} TB"
        except:
            return "Unknown"
    
    @staticmethod
    def download_file(
        url: str,
        output_path: str,
        progress_callback: Optional[callable] = None
    ) -> bool:
        """
        下载文件
        
        Args:
            url: 下载地址
            output_path: 保存路径
            progress_callback: 进度回调函数 (block_num, block_size, total_size)
        
        Returns:
            bool: 是否成功
        """
        try:
            # 确保输出目录存在
            FileUtils.ensure_dir(Path(output_path).parent)
            
            # 下载文件
            urllib.request.urlretrieve(url, output_path, progress_callback)
            return True
        except Exception as e:
            print(f"[错误] 下载文件失败: {e}")
            return False
    
    @staticmethod
    def is_image_file(file_path: str) -> bool:
        """
        判断是否为图片文件
        
        Args:
            file_path: 文件路径
        
        Returns:
            bool: 是否为图片文件
        """
        image_extensions = {'.png', '.jpg', '.jpeg', '.bmp', '.tiff', '.webp'}
        return Path(file_path).suffix.lower() in image_extensions
    
    @staticmethod
    def get_temp_dir() -> Path:
        """
        获取临时目录
        
        Returns:
            Path: 临时目录路径
        """
        temp_dir = Path(os.getenv('TEMP', '/tmp')) / 'sam_tool'
        FileUtils.ensure_dir(temp_dir)
        return temp_dir

